# -*- coding: utf-8 -*-

import cgi
import os
import hashlib
import Cookie
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from django.template import loader

from model import People, Message
from mycookie import Cookies

# cookie过期小时数
cookie_max_hours = 12
cookie_max_age = 60 * 60 * (cookie_max_hours + 8)

class Helper():
    """
    help class, provide some common functions
    """
    @staticmethod
    def get_current_user(handler):
        cookies = Cookies(handler, max_age=cookie_max_age)
        userlist = None
        
        try: 
            user_name = cookies["name"];
            user_password = cookies["password"];
            userlist = db.GqlQuery("SELECT * FROM People WHERE name = :1 AND password = :2", user_name, user_password)
        except:
            logging.error("inquire user error.")
            
        return userlist

class MainHandler(webapp.RequestHandler):
    def get(self):       
        userlist = Helper.get_current_user(self)
        if userlist and userlist.count() > 0:
            currentuser = userlist.get()
            url = "/logout"
            url_linktext = u"注销"
            login = True
            signin_url = "/register"
        else:
	    currentuser = None
            url = "/login"
            url_linktext = u"登录"
            login = False
            signin_url = "/register"
            
        peoples = db.GqlQuery("SELECT * FROM People ORDER BY onlinetime DESC LIMIT 10")
        
        template_values = {
            "peoples" : peoples,
            "currentuser": currentuser,
            "url" : url,
            "url_linktext" : url_linktext,
            "signin_url" : signin_url,
            "login" : login,
        }
        
        path = os.path.join(os.path.dirname(__file__), "index.html")
        self.response.out.write(template.render(path, template_values))

class Online(webapp.RequestHandler):
    def post(self):
        period = int(self.request.get("period"))
                
        userlist = Helper.get_current_user(self)
        if userlist and userlist.count() > 0:
            user = userlist.get()
            user.onlinetime += period;
            user.put()
        
class Register(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), "register.html")
        template_value = {
                "url" : '/Bo6li3du',
                }
        self.response.out.write(template.render(path, template_value))
    
    def post(self):
        _name = self.request.get("name")
	if _name == "":
	    self.redirect("/register")
	    return
        _password = self.request.get("password")
	if _password == "":
	    self.redirect("/register")
	    return
        _nickname = self.request.get("nickname")
	if _nickname == "":
	    self.redirect("/register")
	    return
	
        # md5密码加密
        md5 = hashlib.md5(_password)
        md5_pwd = md5.hexdigest()
        people = People(name=_name, password=md5_pwd, nickname=_nickname)
        people.signature = self.request.get("signature")
        people.put()
        
        # 注册成功跳转到登录页
        self.redirect("/login")

class Login(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), "login.html")
        self.response.out.write(template.render(path, {}))
        
    def post(self):
        user_name = self.request.get("name")
        user_password = self.request.get("password")
        md5 = hashlib.md5(user_password)
        md5_pwd = md5.hexdigest()
        users = db.GqlQuery("SELECT * FROM People WHERE name = :1 AND password = :2", user_name, md5_pwd)
        
        # 如果用户存在，将name, password写入cookie
        if users.count() > 0:
            cookies = Cookies(self, max_age=cookie_max_age)
            cookies["name"] = user_name;
            cookies["password"] = md5_pwd;
            
            # 登录成功，返回主页
            self.redirect("/")
        else:
            # TODO: 弹出登录失败提示框
            #self.response.out.write("<script type='text/javascript'>Login Failed!</script>")
            self.redirect("/login")

class Logout(webapp.RequestHandler):
    def get(self):
        # 用户注销，删除cookie，返回主页
        cookies = Cookies(self, max_age=cookie_max_age)
        del cookies["name"]
        del cookies["password"]
        self.redirect("/")

class MessageBoard(webapp.RequestHandler):
    def get(self):
        userlist = Helper.get_current_user(self)
        if userlist and userlist.count() > 0:
            __nickname = userlist.get().nickname
        else:
            __nickname = u"匿名"
        messages = db.GqlQuery("SELECT * FROM Message ORDER BY date DESC LIMIT 5")        
        #messages = db.GqlQuery("SELECT * FROM Message WHERE nickname =:nickname ORDER BY date DESC LIMIT 5",nickname=__nickname)        
        
        useajax = self.request.get("useajax")
        if not useajax:
            template_values = {
                "messages" : messages,
            }
            path = os.path.join(os.path.dirname(__file__), "message.html")
            self.response.out.write(template.render(path, template_values))
        else:
            # 拼接xml文档，异步返回xml，产生ajax效果
            self.response.headers['Content-Type'] = 'text/xml'
            self.response.headers['Cache-Control'] = 'no-cache'
        
            self.response.out.write('<?xml version="1.0"?>\n')
            self.response.out.write('<response>\n')
            for message in messages:
                if message.nickname == __nickname :
                    self.response.out.write('<message>\n')
                    if message.nickname:
                        self.response.out.write('<nickname>%s</nickname>\n' % message.nickname)
                    else:
                        self.response.out.write(u'<author>匿名用户</author>\n')
                    self.response.out.write('<content>%s</content>\n' % message.content)
                    self.response.out.write('</message>\n')
            self.response.out.write('</response>\n')
    
    def post(self):
        userlist = Helper.get_current_user(self)
        if userlist and userlist.count() > 0:
            __nickname = userlist.get().nickname
        else:
            __nickname = u"匿名"
        message = Message(nickname=__nickname)
        message.content = self.request.get("content")
        message.put()

def main():
    application = webapp.WSGIApplication(
                                        [  ('/', MainHandler),
                                            ('/Bo6li3du', Register),
                                            ('/login', Login),
                                            ('/logout', Logout),
                                            ('/online', Online),
                                            ('/messageboard', MessageBoard),
                                            ],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

